import Vue from "vue";
import axios from "axios";
import { Toast } from "vant";
import router from "@/router";

const defaultOptions = {
  // withCredentials: true,
  timeout: 30000,
};

axios.interceptors.request.use((config) => {
  let token = localStorage.getItem("TOKEN");
  if (token && config.url.indexOf("/dfs/group1/upload") === -1) {
    config.headers["X-Token"] = token;
  }
  return config;
});

axios.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      const { data } = response;
      if (data.code === 200) {
        return data.data;
      } else if (data.code === 401) {
        localStorage.removeItem("TOKEN");
        router.replace("/");
        return {};
      } else if (data.retcode === 0) {
        return data;
      } else {
        Toast.fail(data.msg);
        return {};
      }
    }
  },
  (error) => {
    if (error.response.data.code === 401) {
      localStorage.removeItem("TOKEN");
      router.replace("/login");
      return {};
    }
    return Promise.resolve(error.response);
  },
);

export default {
  get: (url, data, options = {}) => {
    return new Promise((resolve) => {
      axios(url, {
        method: "get",
        params: data || {},
        ...defaultOptions,
        ...options,
      }).then((res) => {
        resolve(res);
      });
    });
  },
  post: (url, data, options = {}) => {
    return new Promise((resolve) => {
      axios(url, {
        method: "post",
        data: data || {},
        headers: {
          "Content-Type": "application/json; charset=utf-8",
        },
        ...defaultOptions,
        ...options,
      }).then((res) => {
        resolve(res);
      });
    });
  },
};
